/**
 * Captain
 * © 2017 Captain copyright，All rights reserved.
 * http://www.sccaptain.com.cn
 * 
 * JAVA : 8
 * 文  件  名: WebAuthenticationDetails.java
 * 创  建  人: Roc Zheng (roc.djz@gmail.com)
 * 创建时间: 2017年8月2日 上午9:48:16
 * 版         本: 1.0.0
 * 备         注:
 * 修订历史:
 */
package com.material.c2c.web.sys.security;

import javax.servlet.http.HttpServletRequest;

import com.cpt.framework.web.util.HttpRequestUtils;

/**
 * 
 * 
 * @since 1.0
 * @version 1.0
 * @author Roc Zheng (roc.djz@gmail.com)
 */
public class WebAuthenticationDetails extends org.springframework.security.web.authentication.WebAuthenticationDetails {
  private static final long serialVersionUID = 1L;

  private final String realRemoteAddress;

  /**
   * 初始化 {@link WebAuthenticationDetails} 类的新实例。
   * @param request
   */
  public WebAuthenticationDetails(HttpServletRequest request) {
    super(request);

    this.realRemoteAddress = HttpRequestUtils.getRealRemoteAddr(request);
  }

  /**
   * {@inheritDoc}
   * <p>
   * <b>另注：已处理代理访问的情况。</b>
   * </p>
   * 
   * @since 1.0
   * @version 1.0
   * @author Roc Zheng (roc.djz@gmail.com)
   */
  @Override
  public String getRemoteAddress() {
    return realRemoteAddress;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean equals(Object obj) {
    if (obj instanceof WebAuthenticationDetails) {
      WebAuthenticationDetails rhs = (WebAuthenticationDetails) obj;
      if ((realRemoteAddress == null) && (rhs.getRemoteAddress() != null)) {
        return false;
      }

      if ((realRemoteAddress != null) && (rhs.getRemoteAddress() == null)) {
        return false;
      }

      if (realRemoteAddress != null) {
        if (!realRemoteAddress.equals(rhs.getRemoteAddress())) {
          return false;
        }
      }

      String sessionId = getSessionId();
      if ((sessionId == null) && (rhs.getSessionId() != null)) {
        return false;
      }

      if ((sessionId != null) && (rhs.getSessionId() == null)) {
        return false;
      }

      if (sessionId != null) {
        if (!sessionId.equals(rhs.getSessionId())) {
          return false;
        }
      }

      return true;
    }

    return false;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public int hashCode() {
    int code = 7654;

    if (this.realRemoteAddress != null) {
      code = code * (this.realRemoteAddress.hashCode() % 7);
    }

    if (this.getSessionId() != null) {
      code = code * (this.getSessionId().hashCode() % 7);
    }

    return code;
  }
}
